package com.dykj.fireFighting.web.controller;
import com.dykj.fireFighting.api.fire.contractMessage.dto.ContractMessageDto;
import com.dykj.fireFighting.api.fire.contractMessage.entity.ContractMessage;
import com.dykj.fireFighting.api.fire.contractMessage.service.IContractMessageService;
import com.dykj.fireFighting.api.fire.contractMessage.vo.ContractMessagesVo;
import com.dykj.fireFighting.api.fire.contractNotifyRecord.service.IContractNotifyRecordService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 维保合同
 */
@Slf4j
@Api(value = "维保合同", tags = {"维保合同"})
@RestController
@RequestMapping("contract")
public class ContractMessageController {
    @DubboReference
    private IContractMessageService iContractMessageService;
    @DubboReference
    private IContractNotifyRecordService iContractNotifyRecordService;


    @AutoLog(value = "获取合同列表")
    @ApiOperation(value = "获取合同列表", notes = "获取合同列表")
    @GetMapping("/getList")
    @RequiresPermissions("contract/list")
    public CommonResult<PageVo<ContractMessagesVo>> queryList(ContractMessageDto contractMessageDto) {
        LoginUserVo loginUserVo = ShiroUtil.getUser();
        if(loginUserVo.getUserType()!=0)
        {
            contractMessageDto.setWeibaoUnitsCode(loginUserVo.getEnterpriseId().toString());
        }
        contractMessageDto.setIsDel("0");
        PageVo<ContractMessagesVo> page = iContractMessageService.queryList(contractMessageDto);
        return CommonResult.success(page);
    }
    /**
     * 删除企业信息
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除合同信息", notes = "删除合同信息")
    @ApiImplicitParam(paramType = "query", name = "ids", value = "企业ID数组", dataType = "String", required = true, allowMultiple = true)
    @PostMapping("/delete")
    @RequiresPermissions("contract/delete")
    public CommonResult deleteBatchIds(@RequestBody String[] ids) {
        iContractMessageService.removeByIds(Arrays.asList(ids));
        return CommonResult.success("删除成功");
    }


    /**
     * 保存企业信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "保存企业信息", notes = "保存企业信息")
    @PostMapping("/save")
    @RequiresPermissions("contract/save")
    public CommonResult save(@Valid @RequestBody ContractMessage contractMessage) {
        try {

            int num=iContractMessageService.querySameContractNumSize(contractMessage.getContractNumber().trim(),null);
            if(num>0)
            {
                return CommonResult.failed("合同号存在重复情况,请修改后提交");
            }

            String title = "添加成功";
            LoginUserVo loginUserVo = ShiroUtil.getUser();
            contractMessage.setId(UUIDUtils.get32UUID());
            contractMessage.setCreateDate(new Date());
            contractMessage.setWeibaoUnitsCode(loginUserVo.getEnterpriseId().toString());
            contractMessage.setCreateBy(ShiroUtil.getUser().getLoginName());
            contractMessage.setContractNumber(contractMessage.getContractNumber().trim().toString());
            if(null !=contractMessage.getSysTypeList() && contractMessage.getSysTypeList().size()>0){
                List<String> sysTypeList = contractMessage.getSysTypeList();
                String join = Joiner.on(",").join(sysTypeList);
                contractMessage.setSysType(join);
            }
            boolean isOk = iContractMessageService.save(contractMessage);
            if (isOk) {
                iContractNotifyRecordService.addContractNotify(contractMessage);
                return CommonResult.success(title);
            } else {
                return CommonResult.failed("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("运行异常，请联系管理员");
        }

    }


    /**
     * 保存企业信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "保存合同信息", notes = "保存合同信息")
    @GetMapping("/info/{id}")
    @RequiresPermissions("contract/info")
    public CommonResult<ContractMessagesVo> info(@PathVariable String id) throws Exception{
          ContractMessage contractMessage=iContractMessageService.getById(id);
        List<String> strings = Arrays.asList(contractMessage.getSysType().split(","));
        contractMessage.setSysTypeList(strings);
          if(contractMessage!=null)
          {
              ContractMessagesVo vo=new ContractMessagesVo();
              BeanUtils.copyProperties(contractMessage,vo);

              return CommonResult.success(vo);

          }
          return null;

    }

    /**
     * 修改企业信息
     *
     *
     * @return
     */
    @ApiOperation(value = "修改合同信息", notes = "修改合同信息")
    @PostMapping("/update")
    @RequiresPermissions("contract/update")
    public CommonResult update(@Valid @RequestBody ContractMessage contractMessage) {
        try {

            int num=iContractMessageService.querySameContractNumSize(contractMessage.getContractNumber().trim(),contractMessage.getId());
            if(num>0)
            {
                return CommonResult.failed("合同号存在重复情况,请修改后提交");
            }
            contractMessage.setContractNumber(contractMessage.getContractNumber().trim().toString());
            if(null !=contractMessage.getSysTypeList() && contractMessage.getSysTypeList().size()>0){
                    List<String> sysTypeList = contractMessage.getSysTypeList();
                    String join = Joiner.on(",").join(sysTypeList);
                    contractMessage.setSysType(join);
            }

            iContractMessageService.updateById(contractMessage);
            iContractNotifyRecordService.addContractNotify(contractMessage);
           return CommonResult.success("修改成功");

        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("运行异常，请联系管理员");
        }
    }

    /**
     * 获取本维保单位的合同
     * @return
     */
    @RequestMapping("/getSomeContract")
    public CommonResult getSomeContract(String socialUnitsCode){

        HashMap<String, Object> params = new HashMap<>(16);
        params.put("weibaoUnitsCode",ShiroUtil.getUser().getEnterpriseId().toString());
        if(null !=socialUnitsCode && StringUtils.isNotBlank(socialUnitsCode)){
            params.put("socialUnitsCode",socialUnitsCode);
        }
       List<ContractMessagesVo> list=iContractMessageService.getSomeContract(params);

        return CommonResult.success(list);
    }
    /**
     * 获取本维保单位的合同de社会单位
     * @return
     */
    @RequestMapping("/getUnitList")
    public CommonResult getUnitList(String contractId){

        HashMap<String, Object> params = new HashMap<>(16);
        params.put("weibaoUnitsCode",ShiroUtil.getUser().getEnterpriseId().toString());
        if(null !=contractId && StringUtils.isNotBlank(contractId)){
            params.put("contractId",contractId);
        }
        List<ContractMessagesVo> list=iContractMessageService.getUnitList(params);

        return CommonResult.success(list);
    }
}
